import ol from 'openlayers'

let layerHelper = {};

function stringDivider(str, width, spaceReplacer) {
    if (str.length > width) {
        var p = width;
        for (; p > 0 && (str[p] != ' ' && str[p] != '-'); p--) { }
        if (p > 0) {
            var left;
            if (str.substring(p, p + 1) == '-') {
                left = str.substring(0, p + 1);
            } else {
                left = str.substring(0, p);
            }
            var right = str.substring(p + 1);
            return left + spaceReplacer + stringDivider(right, width, spaceReplacer);
        }
    }
    return str;
}

function createXYZLayer(options) {
    var title = options.title;
    var opacity = options.opacity || 1;
    var maxResolution = options.maxResolution || undefined;
    var minResolution = options.minResolution || undefined;

    return new ol.layer.Tile({
        title: title,
        opacity: opacity,
        minResolution: minResolution,
        maxResolution: maxResolution,
        visible: options.visible || false,
        style: options.styleFunction,
        zIndex: options.zIndex || 0,
        source: new ol.source.XYZ(options)
    });
}

function createGaodeXYZLayer(options) {
    var title = options.title;
    var opacity = options.opacity || 1;
    var maxResolution = options.maxResolution || undefined;
    var minResolution = options.minResolution || undefined;

    return new ol.layer.Tile({
        title: title,
        opacity: opacity,
        minResolution: minResolution,
        maxResolution: maxResolution,
        visible: options.visible || false,
        style: options.styleFunction,
        zIndex: options.zIndex || 0,
        source: new ol.source.TileImage(options)
    });
}

function createARCGISTILELayer(options) {
    var title = options.title;
    var opacity = options.opacity || 1;
    var maxResolution = options.maxResolution || undefined;
    var minResolution = options.minResolution || undefined;

    return new ol.layer.Tile({
        title: title,
        opacity: opacity,
        minResolution: minResolution,
        maxResolution: maxResolution,
        visible: options.visible || false,
        zIndex: options.zIndex || 0,
        source: new ol.source.TileArcGISRest({
            url: options.url
        })
    });
}

function createBAIDUTILELayer(options) {
    var title = options.title;
    var opacity = options.opacity || 1;
    var maxResolution = options.maxResolution || undefined;
    var minResolution = options.minResolution || undefined;
    var projection = ol.proj.get("EPSG:3857");
    var resolutions = [];
    for (var i = 0; i < 19; i++) {
        resolutions[i] = Math.pow(2, 18 - i);
    }
    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions
    });

    return new ol.layer.Tile({
        title: title,
        opacity: opacity,
        minResolution: minResolution,
        maxResolution: maxResolution,
        visible: options.visible || false,
        zIndex: options.zIndex || 0,
        source: new ol.source.TileImage({
            projection: projection,
            tileGrid: tilegrid,
            tileUrlFunction: function (tileCoord, pixelRatio, proj) {
                if (!tileCoord) {
                    return "";
                }
                var z = tileCoord[0];
                var x = tileCoord[1];
                var y = tileCoord[2];

                if (x < 0) {
                    x = "M" + (-x);
                }
                if (y < 0) {
                    y = "M" + (-y);
                }

                return options.url + "/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1";
            }
        })
    });
}

function createVectorLayer(options) {
    var title = options.title;
    var opacity = options.opacity || 1;
    var source = options.sourceObject;
    var maxResolution = options.maxResolution || undefined;
    var minResolution = options.minResolution || undefined;
    if (options.url != '' && options.url != null && options.url != undefined && typeof (options.url) != 'function') {
        if (options.url.indexOf("?") != -1) {

        } else {
            options.url = options.url + '?where=1%3D1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=3857&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&f=pjson';
        }
    }

    return new ol.layer.Vector({
        title: title,
        opacity: opacity,
        minResolution: minResolution,
        maxResolution: maxResolution,
        visible: options.visible || false,
        style: options.styleFunction,
        source: source || new ol.source.Vector(options),
        zIndex: options.zIndex || 0,
    });
}

// 创建WMS图层
function createWMSLayer(options) {
    // 例
    //new ol.layer.Image({
    //    source: new ol.source.ImageWMS({
    //        crossOrigin: 'anonymous',
    //        params: { 'LAYERS': '5,6,10' },
    //        serverType: 'mapserver',
    //        url: 'http://192.168.0.205:6081/proxy.ashx?http://192.168.1.193:6080/arcgis/services/hbmap/MapServer/WMSServer',
    //        projection: 'EPSG:3785'
    //    })
    //});

    var layer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
            crossOrigin: 'anonymous',
            params: options.params,
            serverType: 'mapserver',
            url: options.url,
            projection: options.projection
        }),
        title: options.title,
        visible: options.visible,
        zIndex: options.zIndex || 0,
    });
    return layer;
};

// 在线天地图
function createTianDiTuLayer(options) {
    var projection = ol.proj.get('EPSG:102100');
    var projectionExtent = projection.getExtent();
    var size = ol.extent.getWidth(projectionExtent) / 256;
    var resolutions = new Array(18);
    var matrixIds = new Array(18);
    for (var z = 1; z < 19; z++) {
        // generate resolutions and matrixIds arrays for this WMTS
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
    }
    var layer = new ol.layer.Tile({
        title: options.title,
        visible: options.visible,
        zIndex: options.zIndex || 0,
        opacity: options.opacity || 1,
        source: new ol.source.WMTS({
            //url: 'http://t0.tianditu.com/img_w/wmts',
            url: options.url,
            layer: options.layer,//'img',
            matrixSet: options.matrixSet,//'w',
            format: 'tiles',
            style: 'default',
            projection: projection,
            tileGrid: new ol.tilegrid.WMTS({
                origin: ol.extent.getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds
            })
        })
    });
    return layer;
}

layerHelper.createLayer = function (options) {
    var layer = null;
    if ('object' == typeof options.style) {
        var style = options.style;
        options.styleFunction = function (feature, resolution) {
            return style;
        }
    }

    var source = options.source || '';
    if ("XYZ" == source) {
        layer = createXYZLayer(options);
    }
    else if ("GaodeXYZ" == source) {
        layer = createGaodeXYZLayer(options);
    }
    else if ("arctile" == source) {
        layer = createARCGISTILELayer(options);
    }
    else if ("baidutile" == source) {
        layer = createBAIDUTILELayer(options);
    }
    else if ("WMS" == source) {
        layer = createWMSLayer(options)
    }
    else if("TDTTile" == source){
        layer = createTianDiTuLayer(options)
    }
    else if ("Vector" == source) {
        var defaultTextStyle = {
            text: 'normal',
            align: "left",
            baseline: "middle",
            rotation: 0.0,
            font: "Arial",
            weight: "normal",
            size: "12px",
            offsetX: 10,
            offsetY: 0,
            color: "#000000",
            outline: "#ffffff",
            outlineWidth: 3,
            maxreso: 38400
        };
        var marking = options.marking || '';
        if (marking.length > 0) {
            var textStyle = options.textStyle || {};
            for (var key in defaultTextStyle) {
                if (!textStyle[key]) {
                    textStyle[key] = defaultTextStyle[key];
                }
            }

            var getText = function (value, resolution, style) {
                var maxResolution = parseFloat(style.maxreso);
                var text = marking;
                var type = style.text;
                for (var key in value) {
                    text = text.replace(("[" + key + "]"), value[key]);
                }

                if (resolution > maxResolution) {
                    text = '';
                } else if (type == 'hide') {
                    text = '';
                } else if (type == 'shorten') {
                    text = text.trunc(12);
                } else if (type == 'wrap') {
                    text = stringDivider(text, 16, '\n');
                }
                if (text == null || text == undefined || text == "") {
                    text = "";
                }
                return text;
            };

            options.text = function (feature, resolution) {
                var value = feature.getProperties() || null;
                if (value) {
                    var text = getText(value, resolution, textStyle);
                    return new ol.style.Text({
                        textAlign: textStyle.align,
                        textBaseline: textStyle.baseline,
                        font: textStyle.weight + ' ' + textStyle.size + ' ' + textStyle.font,
                        text: text,
                        fill: new ol.style.Fill({
                            color: textStyle.color
                        }),
                        stroke: new ol.style.Stroke({
                            color: textStyle.outline,
                            width: parseInt(textStyle.outlineWidth, 10)
                        }),
                        offsetX: parseInt(textStyle.offsetX, 10),
                        offsetY: parseInt(textStyle.offsetY, 10),
                        rotation: parseFloat(textStyle.rotation)
                    });
                }
            }

            if ('function' == typeof options.styleFunction) {
                var fn = options.styleFunction;
                options.styleFunction = function (feature, resolution) {
                    var style = fn(feature, resolution);
                    try {
                        style.setText(options.text(feature, resolution));
                    } catch (e) { }

                    return style;
                }
            }
        }

        layer = createVectorLayer(options);
    }

    return layer;
}

layerHelper.createGroup = function (options) {
    var layers = [];
    var title = options.title;
    var items = options.layers;
    for (var i = 0, len = items.length - 1; len >= 0; len--) {
        var layer = layerHelper.createLayer(items[len]);
        if (layer) {
            layers.push(layer);
        }
    }

    if (layers.length == 0) {
        return null;
    }
    return new ol.layer.Group({
        title: title,
        layers: layers
    });
}

export default layerHelper
